# == Schema Information
# Schema version: 20080914230643
#
# Table name: people
#
#  id            :integer(4)      not null, primary key
#  name          :string(255)     default(""), not null
#  email_address :string(255)     default(""), not null
#  location      :string(255)     default(""), not null
#  url           :string(255)
#  created_at    :datetime
#  updated_at    :datetime
#

class Person < ActiveRecord::Base
	has_one :invitation_request
	
	validates_presence_of :name, :email_address, :location
	validates_format_of	:email_address,
											:with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i,
											:message => "email address isn't formatted correctly",
											:unless => Proc.new { |p| p.email_address.blank? }
	validates_uniqueness_of :email_address,
													:message => "has already been registered"

	def first_name
		name.split()[0]
	end

	def url
		self[:url]
	end

	def url=(url)
		if url.blank?
			self[:url] = nil
			return
		end
		
		if url.index('http://') != 0
			url = 'http://' + url
		end
		
		self[:url] = url
	end

	def validate
		if url.blank?
			return
		end
		
	  begin
	    uri = URI.parse(url)
	    if uri.class != URI::HTTP
	      errors.add(:url, 'Only HTTP protocol addresses can be used')
	    end
	  rescue URI::InvalidURIError
	      errors.add(:url, 'URL isn\'t formatted correctly')
	  end
	end
end
